import os
import numpy as np
import matplotlib.pyplot as plt

FILE_DIR = os.getcwd()

class Sampling:
    def __init__(self, sampling_size=int(1e6)):
        self.theorectical_x = np.linspace(0, 1, 500)
        self.theorectical_y = 1.5 * np.sqrt(self.theorectical_x)
        self.epsilon = np.random.rand(sampling_size)
        self.y = np.random.rand(sampling_size) * 1.5
        for method in ["direct", "selection"]:
            self.draw("{:s}_sampling".format(method))
    
    def direct_sampling(self):
        return np.power(self.epsilon, 2 / 3)

    def selection_sampling(self):
        phi = 1.5 * np.sqrt(self.epsilon)
        return self.epsilon[phi >= self.y]
    
    def draw(self, method):
        sampling_result = getattr(self, method)()
        plt.clf()
        plt.title(method)
        plt.plot(self.theorectical_x, self.theorectical_y, label="Theorectical")
        plt.hist(sampling_result, 100, density=True, label="Practical")
        plt.legend()
        plt.xlabel("X")
        plt.ylabel("f(x)/g(x)")
        plt.savefig(os.path.join(FILE_DIR, "{:s}.png".format(method)))
        
if __name__ == "__main__":
    S = Sampling()